layui.define(['amis', 'api', 'utils'], function (exports) {

    var MOD_NAME = 'resource_toolbar',
        schema = layui.schema,
        listeners = layui.listener,
        schema_render = layui.schema_render,
        amis = layui.amis,
        utils = layui.utils,
        api = layui.api,
        resource_toolbar_option,
        $ = layui.jquery;


    /**
     * 资源工具栏_单击树监听器
     * @param {} event 
     * @param {*} treeId 
     * @param {*} treeNode 
     */
    function resource_toolbar_resourceTreeClickListener(event, treeId, treeNode, option, pearBody, resource_tabs_obj) {
        var treeObj = $.fn.zTree.getZTreeObj(treeId)
        var schemaType = treeObj.setting.view.schemaType;
        var metaType = treeNode.data.type.metaType;
        var resourceTypeSchema = schema.get(schemaType);
        var typeSchema = resourceTypeSchema[metaType];
        
        if (typeSchema.toolbar) {
            removeDom({
                elem: '.header-right-toolBar'
            });


            var toolbar = {
                elem: '.header-right-toolBar',
                treeNode: treeNode,
                schemaType: schemaType,
            }



            if (treeNode) {
                var metaType = treeNode.data.type.metaType;
                var resourceTypeSchema = schema.getResource(schemaType);
                var typeSchema = resourceTypeSchema[metaType];

                if (typeSchema.toolbar) {
                    renderToolbar(resource_toolbar_option, typeSchema.toolbar, toolbar);
                }
            }

        }
    }
    

    /**
     * 模块装配
     */
    function configur() {
        listeners.registerResourceTreeClickListener('resource_toolbar_resourceTreeClickListener', resource_toolbar_resourceTreeClickListener);
    }


    var resource_toolbar = function (opt) {
        this.option = opt;
    };



    function removeDom(option) {
        $(option.elem).empty();
    }

    function renderToolbar(option, toolbarSchema, toolbar) {
        var dataList = [{
                "type": "span",
                "tooltip": "预览",
                "label": "",
                "mode": "action",
                "action": {
                    "componentId": "",
                    "args": {
                        "url": option.previewApi,
                        "blank": true
                    },
                    "actionType": "url"
                },
                "icon": "preview"
            },

        ]
        var preview = {
            "type": "span",
            "tooltip": "预览",
            "label": "",
            "mode": "action",
            "action": {
                "componentId": "",
                "args": {
                    "url": option.previewApi,
                    "blank": false
                },
                "actionType": "url"
            },
            "icon": "preview"
        }

        var formatToolbarSchema = $.extend(true, [], toolbarSchema);
        // formatToolbarSchema.push(preview)
        dataList.forEach((item) => {
            formatToolbarSchema.push(item)
        })

        var idPreFix = "resource_toolbar_";
        var dom = `<li class="layui-nav-item header-right-toolBar">
            ${formatToolbarSchema.map(function(item, i){
                var id = idPreFix + i;
                return  `
            <span id="${id}" class="icon ${item.icon}_active" title="${item.tooltip}"></span>
            `
            }).join('')}
        </li>`
        if ($('.layui-layout-right').length) {
            $('.layui-layout-right').children().eq(0).remove()
            $('.layui-layout-right').prepend(dom)
        } else {
            var dom = `
            <ul class="layui-nav layui-layout-right"> 
                ${dom}
            </ul>
        `
            $(option.elem).append(dom);
        }



        $(".layui-layout-right").children(":first").find("span").click(function (event) {
            var toolbrObj = toolbar;
            var schemaItemIndex = event.target.id.slice(idPreFix.length);
            var spanSchema = formatToolbarSchema[schemaItemIndex];

            action(event, spanSchema, toolbrObj);
        })

    }

    function renderUser(option, toolbarSchema, toolbar) {

        var dom = `<li class="layui-nav-item layui-hide layui-show-md-inline-block">
                    <a href="javascript:;">
                        <img src="${option.previmg}user.png" class="layui-nav-img">
                        ${option.userName}
                        <i class="layui-icon layui-icon-down layui-nav-more"></i></a>
                    <dl class="layui-nav-child layui-anim layui-anim-upbit">
    <!--                            <dd><a href="">Your Profile</a></dd>-->
                        <dd><a href="javascript:;" id="changePwd">修改密码</a></dd>
                        <dd><a href="${option.logoutApi}">退出</a></dd>
                    </dl>
                </li>`

        $(option.elem + ' .layui-nav.layui-layout-right').append(dom);

        $("#changePwd").click(function () {
            layer.open({
                type: 1,
                title: "修改密码",
                offset: '30%',
                content: "<div id='testDialogContent' style='width: 400px; height: 200px;' align='center'></div>",
                shade: 0.3,
                btn: ['提交', '取消'],
                btn1: function (index, layero) {

                    //debugger
                    var formObject = amisNew.option.amisScoped.getComponentByName("modelForm").getValues();
                    // var formObject = amisNew.option.amisScoped.getComponentById("modelForm").getValues();
                    var changeApi = amisNew.option.schema.api;

                    // let putApi = utils.stringformat(optionApi.url,utils.getGlobalEnv());

                    var optionApi = {
                        enableRootPath: true,
                        type: "PUT",
                        url: utils.stringformat(changeApi.url),
                        data: JSON.stringify(formObject),
                        contentType: 'application/json;charset=UTF-8',
                        success: function (data) {
                            layer.closeAll();
                            layer.msg('操作成功');
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg(XMLHttpRequest.responseJSON.msg);
                        }
                    };

                    api.exec(optionApi)
                },
                cancel: function (layero, index) {
                    layer.closeAll();
                }
            });

            var amisNew = amis.render({
                elem: '#testDialogContent',
                schema: {
                    "type": "form",
                    "controls": [{
                            "type": "password",
                            "name": "oldPass",
                            "label": "旧密码",
                            "required": true,
                            "placeholder": "请输入旧密码",
                            "size": "full",
                            "mode": "horizontal"
                        },
                        {
                            "type": "password",
                            "name": "newPass",
                            "label": "新密码",
                            "required": true,
                            "placeholder": "请输入新密码",
                            "size": "full",
                            "mode": "horizontal"
                        },
                        {
                            "type": "password",
                            "name": "confirmPass",
                            "mode": "horizontal",
                            "label": "新密码",
                            "required": true,
                            "placeholder": "请再次输入新密码",
                            "size": "full"
                        }
                    ],
                    "api": {
                        "method": "put",
                        "url": "${platformUrl}/api/v1/user/changePassWord"
                    },
                    "wrapWithPanel": false,
                    "mode": "normal",
                    "id": "modelForm"
                }
            })

        });
    }

    function action(event, spanSchema, toolbrObj) {

        var id = event.target.id;
        if (spanSchema.mode === 'listener') {
            var listenerName;
            if (spanSchema.listenerName) {
                listenerName = spanSchema.listenerName;
            } else {
                listenerName = id + '_toolbar_listener';
            }
            var listener = listeners.getToolbarListener(listenerName);
            if (listener && typeof listener === 'function') {
                listener(event, spanSchema, toolbrObj)
            }
        } else {
            var schemaRenderOption = {
                schema: spanSchema
            }
            if (toolbrObj) {
                schemaRenderOption.contextData = toolbrObj.treeNode
            }
            schema_render.render(schemaRenderOption);
        }
    }



    var toolbarSchema = [
        // {
        //     "tooltip":"保存",
        //     "label": "",
        //     "mode":"listener",
        //     "listenerName":"createFileListener",
        //     "icon": "save"
        // },
        // {
        //     "type": "span",
        //     "tooltip":"设计",
        //     "label": "",
        //     "mode":"action",
        //     "action": {
        //         "componentId": "",
        //         "args": {
        //             "url": "${contextPath}/view/v1/engine/page/index?builderEngineUrl=${builderEngineUrl}&tenantId=${mid.tenantId}&componentsJsonUrl=${platformUrl}/api/v1/engine/page/model/custom/compoment/default#/edit-before/${mid.id}",
        //             "blank": true
        //         },
        //         "actionType": "url"
        //     },
        //     "icon": "design"
        // },
        // {
        //     "type": "span",
        //     "tooltip":"发布",
        //     "label": "",
        //     "onEvent": {
        //         "click": {
        //         "actions": [
        //         ]
        //         }
        //     },
        //     "icon": "publish"
        // },
        // {
        //     "type": "span",
        //     "tooltip":"预览",
        //     "label": "",
        //     "onEvent": {
        //         "click": {
        //         "actions": [
        //         ]
        //         }
        //     },
        //     "icon": "preview"
        // },
        // {
        //     "type": "span",
        //     "tooltip":"运行",
        //     "label": "",
        //     "onEvent": {
        //         "click": {
        //         "actions": [
        //         ]
        //         }
        //     },
        //     "icon": "run"
        // },
        // {
        //     "type": "span",
        //     "tooltip":"调试",
        //     "label": "",
        //     "onEvent": {
        //         "click": {
        //         "actions": [
        //         ]
        //         }
        //     },
        //     "icon": "debug"
        // },
        // {
        //     "type": "span",
        //     "tooltip":"停止",
        //     "label": "",
        //     "onEvent": {
        //         "click": {
        //         "actions": [
        //         ]
        //         }
        //     },
        //     "icon": "stop"
        // }
    ]
    // 暴露监听器方法
    resource_toolbar.prototype.resource_toolbar_resourceTreeClickListener = resource_toolbar_resourceTreeClickListener
    resource_toolbar.prototype.render = function (opt) {
        var option = {
            elem: opt.elem,
            previewApi: opt.previewApi,
            logoutApi: opt.logoutApi,
            previmg: window.rootPath.replace('/js', '/image'),
            userName: opt.userName
        }
        // addDom(option, toolbarSchema);
        renderToolbar(option, toolbarSchema)
        renderUser(option, toolbarSchema)
        resource_toolbar_option = option;

        return new resource_toolbar(option);
    }



    configur();
    exports(MOD_NAME, new resource_toolbar());
});